<template>
  <a-row>
    <a-col :span="24" class="h-screen relative">
      <div class="relative flex-row align-center justify-center" style="height: calc(100vh - 53px)">
        <div class="hidden">
        <div id="hiprint-printTemplate" class="hiprint-printTemplate"></div>
        </div>
        <div id="preview_content" class="bordered border-gray-400 border-dotted"></div>
      </div>
      <div class="absolute w-full footer flex-row justify-center">
        <!-- 预览/打印 -->
        <a-space :size="'large'">
          <a-button type="primary" @click="print">浏览器打印</a-button>
          <a-button type="success" @click="print2">客户端打印</a-button>
          <a-button type="default" @click="cancel">取消</a-button>
        </a-space>
      </div>
    </a-col>
  </a-row>
</template>

<script>
import {hiprint} from '../index'
import {aProvider} from "@/demo/custom/providers";
let hiprintTemplate;
export default {
  name: "preview",
  data() {
    return {
      template: null,
      // 打印数量
      count: 1,
      id: 0,
      userid: 0,
      paperWidth: 60,
      paperHeight: 40,
      provider: {},
      baseUrl: '',
      urls: {
        getform: '/manage.php/print_setting/form',
        save: '/manage.php/print_setting/save'
      },
      formdata: null,
      printData: {},
      isauto: 0
    }
  },
  created() {
    if (location.hostname == 'localhost') {
      this.baseUrl = 'http://10.211.55.7:8586';
    } else {
      this.baseUrl = ''
    }
    this.id = this.getParamsByKey('id');
    this.userid = this.getParamsByKey('userid');
    this.isauto = this.getParamsByKey('isauto');
    this.init()
  },
  methods: {
    getParamsByKey(key) {
      let url = location.href;
      let queryInfo = url.split('?')[1];
      let queryParams = new URLSearchParams('?'+queryInfo);
      return queryParams.get(key) || 0;
    },
    init() {
      var that = this;
      $.ajax({
        url: this.baseUrl+this.urls.getform,
        data: {
          id: this.id,
          userid: this.userid || 0,
        },
        dataType: 'GET',
        // type: 'JSON',
        async: true,
        complete(res) {
          let response = JSON.parse(res.responseText);
          if (response.code == 0) {
            that.provider = {
              name: '表单打印设置',
              type: 1,
              value: "aProviderModule",
              f: aProvider(response?.data?.provider)
            }
            that.formdata = response?.data?.data;
            let printData = {};
            (response?.data?.provider).forEach(item => {
              printData[item.fields] = item.testData;
            })
            that.printData = printData;
            that.setprint()
          } else {
            that.$message.error(response.msg || '网络错误');
          }
        },
        failure: function (err) {
          that.$message.error(err.msg || '网络错误');
        }
      })
    },
    setprint() {
      let provider = this.provider; //getPrintSetting()
      hiprint.setConfig({
        showSizeBox: false,
      });
      hiprint.init({
        providers: [provider.f]
      });
      let templates = null;
      try {
        if (this.formdata.user_qrcode) {
          templates = JSON.parse(this.formdata.user_qrcode);
          this.curPaper = {type: 'other', width: templates['aProviderModule']['panels'][0]['width'], height: templates['aProviderModule']['panels'][0]['height']}
          this.paperWidth = this.curPaper.width;
          this.paperHeight = this.curPaper.height;
        }
      } catch (e) {
        //
      }
      $("#hiprint-printTemplate").empty(); // 先清空, 避免重复构建
      let template = templates[provider.value] ? templates[provider.value] : {}
      if (template) {
        template['panels'][0]['paperNumberDisabled'] = true;
      }
      hiprintTemplate = new hiprint.PrintTemplate({
        template: template,
        dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
        history: false, // 是否需要 撤销重做功能
      });
      hiprintTemplate.design('#hiprint-printTemplate');
      hiprintTemplate.setPaper(this.paperWidth, this.paperHeight)
      let html = hiprintTemplate.getHtml(this.printData);
      $('#preview_content').html(html);
      if (parseInt(this.isauto) === 1) {
        var t = setInterval(() => {
          if (window.hiwebSocket.opened) {
            clearInterval(t);
            this.print2();
          }
        }, 500)
      }
    },
    cancel() {
      if (window.parent) {
        window.parent.layer.closeAll();
      }
    },
    print() {
      hiprintTemplate.print(this.printData, {}, {});
    },
    print2() {
      if (window.hiwebSocket.opened) {
        hiprintTemplate.print2(this.printData, {}, {printer: '', title: ''});
        return;
      }
      this.$error({
        title: "客户端未连接",
        content: (h) => (
            <div>
              客户端连接失败！
              <br />
              请确保客户端已下载，并
              <a href="hiprint://" target="_blank">运行</a>
              打印服务！
            </div>
        ),
      });
    }
  }
}
</script>
<style scoped lang="less">
.footer {
  bottom: 0;
    padding: 8px 20px;
    background-color: #ecf0f1;
    height: auto;
    min-height: 53px;
    text-align: inherit !important;
}
</style>
